package com.study.sfd.person.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class PasswordUtils
{
    public static String hashPassword(String password)
    {
        String hashedPassword = null;
        try {
            // 生成随机盐
            SecureRandom random = new SecureRandom();
            byte[] salt = new byte[16];
            random.nextBytes(salt);
            // 将盐与密码组合后进行哈希
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(salt);
            byte[] hash = md.digest(password.getBytes(StandardCharsets.UTF_8));
            // 将盐和哈希值进行组合存储
            String saltString = Base64.getEncoder().encodeToString(salt);
            String hashString = Base64.getEncoder().encodeToString(hash);
            hashedPassword = saltString + "$" + hashString;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hashedPassword;
    }

    public static boolean verifyPassword(String password, String hashedPassword)
    {
        boolean isValid = false;
        try {
            // 提取盐和哈希值
            String[] parts = hashedPassword.split("\\$");
            String saltString = parts[0];
            String hashString = parts[1];
            byte[] salt = Base64.getDecoder().decode(saltString);
            byte[] hash = Base64.getDecoder().decode(hashString);
            // 将盐与密码组合后进行哈希
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(salt);
            byte[] newHash = md.digest(password.getBytes(StandardCharsets.UTF_8));
            // 验证哈希值是否一致
            isValid = MessageDigest.isEqual(hash, newHash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return isValid;
    }

    public static void main(String[] args)
    {
        String password = "password123";
        String hashedPassword = hashPassword(password);
        System.out.println("Hashed Password: " + hashedPassword);
        boolean isValid = verifyPassword(password, hashedPassword);
        System.out.println("Password Valid: " + isValid);
    }
}
